package com.smarth.zhizulian.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.smarth.zhizulian.R;
import com.smarth.zhizulian.activity.AgentWebActivity;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.app.EventFragment;
import com.smarth.zhizulian.bean.BaseEntity;
import com.smarth.zhizulian.bean.Page;
import com.smarth.zhizulian.bean.collection.CollectionIndex;
import com.smarth.zhizulian.entity.EventBean;
import com.smarth.zhizulian.http.KumaHttp;
import com.smarth.zhizulian.http.observer.ProgressObserver;
import com.smarth.zhizulian.http.utils.RxCompos;
import com.smarth.zhizulian.utils.GlideUtils;
import com.smarth.zhizulian.utils.GsonUtils;
import com.smarth.zhizulian.utils.listhelper.RefreshHelper;
import com.smarth.zhizulian.utils.listhelper.impl.adapter.RListDataAdapter;
import com.smarth.zhizulian.utils.listhelper.impl.model.HttpListDataModel;
import com.smarth.zhizulian.utils.listhelper.inter.ResponseSender;
import com.smarth.zhizulian.view.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * Created by 18865 on 2018/2/8.
 */

public class FavoriteVideoFragment extends EventFragment {
    @BindView(R.id.rv_refresh)
    SmartRefreshLayout rvRefresh;
    @BindView(R.id.ll_loadinglayout)
    LoadingLayout llLoadinglayout;
    @BindView(R.id.rc_recyclerview)
    RecyclerView rcRecyclerview;
    private RefreshHelper<List<CollectionIndex>> refreshHelper;
    private RListDataAdapter<CollectionIndex> adapter;
    private boolean isShowCheck;
    @BindView(R.id.ll_control)
    LinearLayout llControl;

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        super.onCreateView(savedInstanceState);
        setBKView(R.layout.fragment_favorite_article);
        initList();
    }

    private void initList() {
        rcRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        refreshHelper = new RefreshHelper<>(mContext, llLoadinglayout, rvRefresh);
        refreshHelper.setDataModel(new HttpListDataModel<List<CollectionIndex>>(mContext) {
            @Override
            public Observable<? extends Page> getObservable(ResponseSender<List<CollectionIndex>> responseSender, int page) {
                return KumaHttp.getService().collectionIndex(1, page).compose(RxCompos.<Page<CollectionIndex>>getBELoginCompos());
            }
        });
        adapter = new RListDataAdapter<CollectionIndex>(R.layout.item_favorite_video) {
            @Override
            protected void convert(BaseViewHolder helper, final CollectionIndex item) {
                CheckBox cb = helper.getView(R.id.cb_checkbox);
                cb.setVisibility(isShowCheck ? View.VISIBLE : View.GONE);
                cb.setChecked(item.isChecked());
                helper.setText(R.id.tv_title, item.getTitle());
                helper.setText(R.id.tv_time, item.getCreateTime());
                helper.setText(R.id.tv_readnum, "阅读 " + item.getReadCount());
                GlideUtils.loadVideo(mContext, item.getImageStr(), (ImageView) helper.getView(R.id.iv_video));
                helper.setText(R.id.tv_videotime, item.getVideoDuration());
            }
        };
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CollectionIndex item = (CollectionIndex) adapter.getItem(position);
                if (isShowCheck) {
                    item.setChecked(!item.isChecked());
                    adapter.notifyDataSetChanged();
                } else {
                    AgentWebActivity.openForVideo(mContext, "" + item.getRelationId());
                }
            }
        });
        refreshHelper.setDataAdapter(adapter, R.id.rc_recyclerview);
        refreshHelper.refresh();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick({R.id.tv_cancel, R.id.tv_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                EventBus.getDefault().post(new EventBean(BaseConfig.EventCode.FAVORITE_CANCEL_NOREFRESH), BaseConfig.EventTag.CANCELEDIT_FAVORITE);
                break;
            case R.id.tv_delete:
                fetchDelete();
                break;
        }
    }

    @Subscriber(tag = BaseConfig.EventTag.CANCELEDIT_FAVORITE)
    private void onEventCancelEdit(EventBean eb) {
        cancelEdit();
        if (eb.getCode() == BaseConfig.EventCode.FAVORITE_CANCEL_REFRESH) {
            refreshHelper.refresh();
        }
    }

    private void cancelEdit() {
        isShowCheck = false;
        adapter.notifyDataSetChanged();
        rvRefresh.setEnableRefresh(true);
        rvRefresh.setEnableLoadmore(true);
        llControl.setVisibility(View.GONE);
        for (CollectionIndex ci : adapter.getData()) {
            ci.setChecked(false);
        }
    }

    private void fetchDelete() {
        List<String> ids = new ArrayList<>();
        for (CollectionIndex ci : adapter.getData()) {
            if (ci.isChecked()) {
                ids.add("" + ci.getId());
            }
        }
        KumaHttp.getService().collectionDeleteColletion(GsonUtils.toJson(ids), 1)
                .compose(RxCompos.getBEAll2LoginCompos())
                .subscribe(new ProgressObserver<BaseEntity>(mContext) {
                    @Override
                    public void onNext(BaseEntity baseEntity) {
                        EventBus.getDefault().post(new EventBean(BaseConfig.EventCode.FAVORITE_CANCEL_REFRESH), BaseConfig.EventTag.CANCELEDIT_FAVORITE);
                    }
                });
    }

    @Subscriber(tag = BaseConfig.EventTag.EDIT_FAVORITE)
    private void onEventEditFavorite(EventBean eb) {
        isShowCheck = true;
        adapter.notifyDataSetChanged();
        rvRefresh.setEnableRefresh(false);
        rvRefresh.setEnableLoadmore(false);
        llControl.setVisibility(View.VISIBLE);
    }
}
